package uk.ac.open.kmi.dyniqx.mvc;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import uk.ac.open.kmi.dyniqx.wrappers.SessionWrapper;

public class QueryInterfaceService {

	public Logger logger = Logger.getLogger("uk.ac.open.kmi.dyniqx.mvc.QueryInterfaceService");
	
	private SessionWrapper sessionWrapper;
	
	public QueryInterfaceService() {}
	
	public void performQuery(HttpServletRequest request) {
		
		HttpSession session = request.getSession(true);

		Date created = new Date(session.getCreationTime());
		Date accessed = new	Date(session.getLastAccessedTime());
		
		this.logger.info("Request received by QueryInterfaceService.");
		this.logger.debug("Session ID: " + session.getId());
		this.logger.debug("Created: " + created);
		this.logger.debug("Last Accessed: " + accessed);

		WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(session.getServletContext());
		BeanFactory factory = (BeanFactory) context;
		this.setSessionWrapper((SessionWrapper) factory.getBean("sessionWrapper"));

		logger.info("SessionWrapper retrieved.");
		
		sessionWrapper.manageQuery(request);
	}
	
	public void setSessionWrapper(SessionWrapper sessionWrapper) {
		this.sessionWrapper = sessionWrapper;
	}
	
	public SessionWrapper getSessionWrapper() {
		return this.sessionWrapper;
	}
}
